import { Middleware } from 'koa'
import jwt from 'jsonwebtoken'
import { noauthPath, secret } from '../config/constant'

const verifyToken: Middleware = async (ctx, next) => {
  //如果有token并且是必要验证的接口就解析参数
  //如果没有token或者是不需要验证的接口就直接放行
  const Authorization = ctx.get('Authorization')
  if (Authorization && !noauthPath.some((item) => item.test(ctx.URL.pathname))) {
    let token = Authorization.split(' ')[1]
    ctx.user = jwt.verify(token, secret)
  }
  await next()
}
export default verifyToken
